import 'dart:async';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';

class NetworkManager {
  static final NetworkManager _instance = NetworkManager._internal();
  factory NetworkManager() => _instance;
  NetworkManager._internal();

  late StreamSubscription<List<ConnectivityResult>> _subscription;
  bool _hasShownDialog = false;
  bool _isInitialized = false;
  ConnectivityResult? _lastResult;

  // 获取当前网络状态
  Future<ConnectivityResult> checkConnectivity() async {
    final results = await Connectivity().checkConnectivity();
    _lastResult = results.first; // 更新最新状态
    return results.first;
  }

  // 是否有网络连接
  Future<bool> hasConnection() async {
    final result = await checkConnectivity(); // 使用 checkConnectivity 获取最新状态
    return result != ConnectivityResult.none;
  }

  // 是否是移动数据
  Future<bool> isMobileData() async {
    final result = await checkConnectivity(); // 使用 checkConnectivity 获取最新状态
    debugPrint(result.toString());
    return result == ConnectivityResult.mobile;
  }

  // 初始化网络监听
  Future<void> init() async {
    if (_isInitialized) return;

    try {
      // 获取初始网络状态
      _lastResult = (await Connectivity().checkConnectivity()).first;
      _handleNetworkChange(_lastResult!);

      // 监听网络变化
      _subscription = Connectivity().onConnectivityChanged.listen((results) {
        _lastResult = results.first;
        _handleNetworkChange(results.first);
        debugPrint('Network changed to: ${results.first}'); // 添加日志
      });

      _isInitialized = true;
    } catch (e) {
      debugPrint('NetworkManager init error: $e');
    }
  }

  // 处理网络变化
  void _handleNetworkChange(ConnectivityResult result) {
    String message = '';
    Color backgroundColor = Colors.black;

    switch (result) {
      case ConnectivityResult.none:
        if (!_hasShownDialog) {
          message = '网络连接已断开';
          backgroundColor = Colors.red;
          _hasShownDialog = true;
        }
        break;
      case ConnectivityResult.mobile:
        if (_hasShownDialog || _lastResult == ConnectivityResult.wifi) {
          message = '已切换到移动数据';
          backgroundColor = Colors.orange;
          _hasShownDialog = false;
        }
        break;
      case ConnectivityResult.wifi:
        if (_hasShownDialog || _lastResult == ConnectivityResult.mobile) {
          message = '已连接到WiFi';
          backgroundColor = Colors.green;
          _hasShownDialog = false;
        }
        break;
      default:
        break;
    }

    if (message.isNotEmpty) {
      _showNetworkToast(message, backgroundColor);
    }
  }

  // 显示网络状态提示
  void _showNetworkToast(String message, Color backgroundColor) {
    SmartDialog.showToast(
      message,
      alignment: Alignment.topCenter,
    );
  }

  // 释放资源
  void dispose() {
    if (_isInitialized) {
      _subscription.cancel();
      _isInitialized = false;
    }
  }
}
